<template>
  <div class="user-profile">
    <!-- 导航栏 -->
    <van-nav-bar
    class="page-nav-bar"
    title="个人信息"
    left-arrow @click-left="$router.back()" />
    <!-- /导航栏 -->
    <input @change="onChange" type="file" hidden ref="inputFile">
    <van-cell @click="$refs.inputFile.click()" title="头像" is-link>
      <van-image
        class="avatar"
        fit="cover"
        round
        :src="user.photo"
      />
    </van-cell>
    <van-cell @click="isShowEdit = true" title="昵称" :value="user.name" is-link />
    <van-cell @click="isShowEditSex = true" title="性别" :value="user.gender ? '女' : '男'" is-link />
    <van-cell @click="isShowEditBirthday = true" title="生日" :value="user.birthday" is-link />

    <!-- 编辑昵称的弹层 -->
    <van-popup v-model="isShowEdit" position="bottom" :style="{ height: '100%' }" >
      <user-edit v-if="isShowEdit" v-model="user.name" @close="isShowEdit = false" />
    </van-popup>

    <!-- 编辑性别的弹层 -->
    <van-popup v-model="isShowEditSex" position="bottom" >
      <user-edit-sex v-if="isShowEditSex" v-model="user.gender" @close="isShowEditSex = false" />
    </van-popup>

    <!-- 编辑生日的弹层 -->
    <van-popup v-model="isShowEditBirthday" position="bottom" >
      <user-edit-birthday v-if="isShowEditBirthday" v-model="user.birthday" @close="isShowEditBirthday = false" />
    </van-popup>

    <!-- 编辑头像的弹层 -->
    <van-popup v-model="isShowEditAvatar" position="bottom" :style="{ height: '100%' }" >
      <user-edit-avatar v-if="isShowEditAvatar" @close="isShowEditAvatar = false" @update-photo="user.photo = $event" :img="imgUrl" />
    </van-popup>
  </div>
</template>

<script>
import { getUserProfile } from '@/api/user.js'
import UserEdit from './components/UserEdit.vue'
import UserEditSex from './components/UserEditSex.vue'
import UserEditBirthday from './components/UserEditBirthday.vue'
import UserEditAvatar from './components/UserEditAvatar.vue'
export default {
  data () {
    return {
      user: {}, // 保存用户个人信息
      isShowEdit: false, // 控制昵称弹层
      isShowEditSex: false, // 控制性别弹层
      isShowEditBirthday: false, // 控制生日的弹层
      isShowEditAvatar: false, // 控制头像的弹层
      imgUrl: ''
    }
  },

  components: { UserEdit, UserEditSex, UserEditBirthday, UserEditAvatar },

  created () {
    this.loadUserProfile()
  },

  methods: {
    async loadUserProfile () {
      try {
        const res = await getUserProfile()
        this.user = res
      } catch (err) {
        console.log('获取用户个人信息失败')
      }
    },
    // 选择文件的输入框发生变化
    onChange (e) {
      if (e.target.value === '') return
      this.isShowEditAvatar = true
      // 如果不进行裁剪，e.target.files[0] 可以直接交给后端
      this.imgUrl = URL.createObjectURL(e.target.files[0])
      e.target.value = ''
    }
  }
}
</script>

<style scoped lang='less'>
.user-profile {
  .avatar {
    width: 60px;
    height: 60px;
  }
  /deep/.van-nav-bar__arrow {
    color: #fff;
  }
}
</style>
